/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.lettuce.core.dynamic.annotation.Param;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.QuestionoptionQueryCriteria;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.domain.vo.QuestionQueryCriteria;
import lombok.RequiredArgsConstructor;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author shitou
* @date 2024-04-21
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "试题管理管理")
@RequestMapping("/api/question")
public class QuestionController {

    private final QuestionService questionService;

    private final QuestionoptionService questionoptionService;

    private final QuestiontypeService questiontypeService;

    private final UserService userService;

    private final TeacherService teacherService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('question:list')")
    public void exportQuestion(HttpServletResponse response, QuestionQueryCriteria criteria) throws IOException {
        questionService.download(questionService.queryAll(criteria), response);
    }
//    getAdminQuestionList
    //获取我的试题占比
    @GetMapping("/queryMyQuestionRito")
    @Log("查询我的试题占比")
    @ApiOperation("查询我的试题占比")
    public ResponseEntity<QuestionRatio> queryMyQuestionRito(){
        questionService.queryMyQuestionRito();
        return new ResponseEntity<>(questionService.queryMyQuestionRito(),HttpStatus.OK);

    }
    //获取学校试题占比
    @GetMapping("/querySchoolQuestionRito")
    @Log("查询学校试题占比")
    @ApiOperation("查询学校试题占比")
    public ResponseEntity<QuestionRatio> querySchoolQuestionRito(){

        return new ResponseEntity<>(questionService.querySchoolQuestionRito(),HttpStatus.OK);
    }

    @GetMapping("/getAdminQuestionList")
    @Log("查询管理员试题管理")
    @ApiOperation("查询管理员试题管理")
    public ResponseEntity<PageResult<Question>> getAdminQuestionList(QuestionQueryCriteria criteria, Page<Object> page){
        PageResult<Question> questionPageObj= questionService.getAdminQuestionList(criteria,page);
        List<Questiontype> questionTypeList = questiontypeService.list();
        if(questionPageObj != null){
            for(Questiontype questiontype : questionTypeList){
                for(Question question:questionPageObj.getContent()){
                    if(Objects.equals(String.valueOf(questiontype.getId()), String.valueOf(question.getQuestionTypeId()))){
                        question.setQuestiontypename(questiontype.getName());
                    }

                    Teacher teacher = teacherService.getById(question.getTeacherId());

                    if(!teacher.getName().isEmpty()){
                        question.setTeacherName(teacher.getName());
                    } else {
                        if(teacher.getUserid()!=null){
                            User user = userService.getById(teacher.getUserid());
                            question.setTeacherName(user.getUsername());
                        }

                    }
                }
            }

        }
        return new ResponseEntity<>(questionPageObj,HttpStatus.OK);
    }

    @GetMapping
    @Log("查询试题管理")
    @ApiOperation("查询试题管理")
//    @PreAuthorize("@el.check('question:list')")
    public ResponseEntity<PageResult<Question>> queryQuestion(QuestionQueryCriteria criteria, Page<Object> page){
        PageResult<Question> questionPageObj= questionService.queryAll(criteria,page);
        List<Questiontype> questionTypeList = questiontypeService.list();
        if(questionPageObj != null){
            for(Questiontype questiontype : questionTypeList){
                for(Question question:questionPageObj.getContent()){
                    if(Objects.equals(String.valueOf(questiontype.getId()), String.valueOf(question.getQuestionTypeId()))){
                        question.setQuestiontypename(questiontype.getName());
                    }

                    Teacher teacher = teacherService.getById(question.getTeacherId());

                    if(teacher!=null && !teacher.getName().isEmpty()){
                        question.setTeacherName(teacher.getName());
                    } else {
                        if(teacher!=null && teacher.getUserid()!=null){
                            User user = userService.getById(teacher.getUserid());
                            question.setTeacherName(user.getUsername());
                        }

                    }
                }
            }

        }
        return new ResponseEntity<>(questionPageObj,HttpStatus.OK);
    }

    @GetMapping("/getMyQuestionList")
    @Log("查询我的试题管理")
    @ApiOperation("查询我的试题管理")
    public ResponseEntity<PageResult<Question>> getMyQuestionList(QuestionQueryCriteria criteria, Page<Object> page){
        PageResult<Question> questionPageObj= questionService.getMyQuestionList(criteria,page);
        List<Questiontype> questionTypeList = questiontypeService.list();
        if(questionPageObj != null){
            for(Questiontype questiontype : questionTypeList){
                for(Question question:questionPageObj.getContent()){
                    if(Objects.equals(String.valueOf(questiontype.getId()), String.valueOf(question.getQuestionTypeId()))){
                        question.setQuestiontypename(questiontype.getName());

                        Teacher teacher = teacherService.getById(question.getTeacherId());

                        if(!teacher.getName().isEmpty()){
                            question.setTeacherName(teacher.getName());
                        } else {
                            if(teacher.getUserid()!=null){
                                User user = userService.getById(teacher.getUserid());
                                question.setTeacherName(user.getUsername());
                            }

                        }
                    }


                }
            }

        }
        return new ResponseEntity<>(questionPageObj,HttpStatus.OK);
    }

    @GetMapping("/getPublicQuestionList")
    @Log("查询公开试题管理")
    @ApiOperation("查询公开试题管理")
    public ResponseEntity<PageResult<Question>> getPublicQuestionList(QuestionQueryCriteria criteria, Page<Object> page){
        criteria.setIsPublish(1);
        criteria.setIsShare(1);
        PageResult<Question> questionPageObj= questionService.queryAll(criteria,page);
        List<Questiontype> questionTypeList = questiontypeService.list();
        if(questionPageObj != null){
            for(Questiontype questiontype : questionTypeList){
                for(Question question:questionPageObj.getContent()){
                    if(Objects.equals(String.valueOf(questiontype.getId()), String.valueOf(question.getQuestionTypeId()))){
                        question.setQuestiontypename(questiontype.getName());

                        Teacher teacher = teacherService.getById(question.getTeacherId());
                        if(!teacher.getName().isEmpty()){
                            question.setTeacherName(teacher.getName());
                        } else {
                            if(teacher.getUserid()!=null){
                                User user = userService.getById(teacher.getUserid());
                                question.setTeacherName(user.getUsername());
                            }

                        }
                    }



                }
            }

        }
        return new ResponseEntity<>(questionPageObj,HttpStatus.OK);
    }

    @GetMapping("/questionMsg")
    @Log("查询试题管理")
    @ApiOperation("查询试题管理")
//    @PreAuthorize("@el.check('question:list')")
    public ResponseEntity<Question> questionMsg(@Param("id") Integer id){

        Question question = questionService.getById(id);
        if(question != null){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("questionid",id);
            List<Questionoption> questionoptions = questionoptionService.list(queryWrapper);
            question.setQuestionoptions(questionoptions);
            return new ResponseEntity<>(question,HttpStatus.OK);
        }
        return null;
    }


    @PostMapping
    @Log("新增试题管理")
    @ApiOperation("新增试题管理")
//    @PreAuthorize("@el.check('question:add')")
    public ResponseEntity<Object> createQuestion(@Validated @RequestBody QuestionDo resources){

        Question question = JSON.parseObject(JSON.toJSONString(resources), Question.class);

        questionService.create(question);
        if(question.getType()<4){
            List<Questionoption> questionoptionList = resources.getOptions();

            for(Questionoption questionoption : questionoptionList){
                questionoption.setQuestionid(question.getId());
                questionoptionService.create(questionoption);
            }
        }


        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改试题管理")
    @ApiOperation("修改试题管理")
//    @PreAuthorize("@el.check('question:edit')")
    public ResponseEntity<Object> updateQuestion(@Validated @RequestBody QuestionDo resources){

        Question question = JSON.parseObject(JSON.toJSONString(resources), Question.class);
        questionService.update(question);

        QuestionoptionQueryCriteria questionoptionQueryCriteria =  new QuestionoptionQueryCriteria();

        if(question.getType()<4){
            questionoptionQueryCriteria.setQuestionid(question.getId());
            List<Questionoption>  questionoption = questionoptionService.queryAll(questionoptionQueryCriteria);
            List<Integer> ids = questionoption.stream().map(Questionoption::getId).collect(Collectors.toList());
            questionoptionService.deleteAll(ids);
            List<Questionoption> questionoptionList = resources.getOptions();

            for(Questionoption questionoption2 : questionoptionList){
                questionoption2.setQuestionid(question.getId());

                questionoptionService.create(questionoption2);
            }
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除试题管理")
    @ApiOperation("删除试题管理")
//    @PreAuthorize("@el.check('question:del')")
    public ResponseEntity<Object> deleteQuestion(@RequestBody List<Integer> ids) {
        questionService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}